package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.constant.ProductConstant;


import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrs;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    // 根据三级分类查询 AttrGroup
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {

        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            System.out.println("key-> " + key);
            wrapper.and((obj) -> {
                // 根据检索条件进一步查询
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        // 判断是否含有catelogId
        if (catelogId == 0) {
            System.out.println("catelogId-> " + catelogId);
            // 查询全部
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );

            return new PageUtils(page);
        } else {
            // 查询是否有检索条件
            wrapper.eq("catelog_id", catelogId);
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }
    }

    /**
     * 获取分组中的所有属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrList(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.list(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        // ①：这种情况查询了多次数据库，不可取！！！
/**        List<AttrEntity> collect = entities.stream().map((item) -> {
 AttrEntity entity = attrService.getById(item.getAttrId());
 return entity;
 }).collect(Collectors.toList());  **/

        // ②：我们先得到所有需要删除的 attrId，然后进行批量删除
        List<Long> attrIds = entities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        // 可能查询为null
        if (attrIds != null) {
            Collection<AttrEntity> attrEntities = attrService.listByIds(attrIds);
            return (List<AttrEntity>) attrEntities;
        }
        return null;
    }

    /**
     * 获取分组中没有关联的基本属性
     *
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils attrNoRelation(Long attrgroupId, Map<String, Object> params) {
        // 1. 查询该分类下的所有分组
        AttrGroupEntity groupEntity = this.getById(attrgroupId);
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", groupEntity.getCatelogId()));
        // 2. 得到所有分组id
        List<Long> groupIds = attrGroupEntities.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        // 3. 通过分组id查询所有的 已经关联的 attr
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> list = attrgroupRelationEntityList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        // 4. 查询该分类下的所有未被关联的属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())  // 基本属性
                .eq("catelog_id", groupEntity.getCatelogId());                       // 在该分类下
        if (list.size() > 0 && list != null) {
            wrapper.notIn("attr_id", list);
        }
        // 添加查询条件
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(item -> {
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> iPage = new Query<AttrEntity>().getPage(params);
        IPage<AttrEntity> page = attrService.page(iPage, wrapper);

        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    /**
     * 添加属性与分组的关联关系
     *
     * @param vos
     */
    @Override
    public void saveBatchRelationVos(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map(item -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(item.getAttrId());
            relationEntity.setAttrGroupId(item.getAttrGroupId());
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationService.saveBatch(collect);
    }

    /**
     * 获取分类下所有分组&关联属性
     *
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrs> attrGroupWithAttrs(Long catelogId) {
        List<AttrGroupEntity> groupEntities = this.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<AttrGroupWithAttrs> collect = groupEntities.stream().map(item -> {
            // 封装所有分组内容
            AttrGroupWithAttrs groupWithAttrs = new AttrGroupWithAttrs();
            BeanUtils.copyProperties(item, groupWithAttrs);
            // 每个分组封装所有属性内容
            List<AttrEntity> attrEntities = attrService.getAttrListByGroupId(item.getAttrGroupId());
            groupWithAttrs.setAttrs(attrEntities);
            return groupWithAttrs;
        }).collect(Collectors.toList());

        return collect;
    }

    // 查询当前spu对应的所有属性的分组信息以及当前分组下所有属性对应的值
    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        AttrGroupDao baseMapper = this.getBaseMapper();
        List<SpuItemAttrGroupVo> spuItemAttrGroupVos = baseMapper.getAttrGroupWithAttrsBySpuId(spuId,catalogId);
        return spuItemAttrGroupVos;
    }

    /**
     * 删除分组中的属性
     *
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrGroupRelationVo> entities = Arrays.asList(vos);
        // 循环删除影响数据库性能，我们在 dao 中编写批量删除语句
        attrAttrgroupRelationDao.deleteBatch(entities);
    }

}